<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';
import { storeToRefs } from '@vben/stores';

import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deviceLogPage } from '#/api/iot/deviceLog';
import { useMqttStore } from '#/store/mqtt';

import { columns, querySchema } from './data';

const useMqtt = useMqttStore();
const { mqttOption } = storeToRefs(useMqtt);

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  showCollapseButton: false,
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
};

const timeHandle = (minute: number, rangeTime: string[]) => {
  let queryStartTime: string = '';
  let queryEndTime: string = '';

  if (minute === 0) {
    if (rangeTime && rangeTime.length === 2) {
      queryStartTime = rangeTime[0] ?? '';
      queryEndTime = rangeTime[1] ?? '';
    }
  } else {
    if (minute) {
      queryEndTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
      queryStartTime = dayjs(new Date())
        .subtract(minute, 'minute')
        .format('YYYY-MM-DD HH:mm:ss');
    }
  }
  return [queryStartTime, queryEndTime];
};

const gridOptions: VxeGridProps = {
  columns,
  keepSource: true,
  toolbarConfig: {
    custom: false,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const [queryStartTime, queryEndTime] = timeHandle(
          formValues.timeInterval,
          formValues.timeIntervalRange,
        );
        return await deviceLogPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          productKey: mqttOption.value.productKey,
          deviceSn: mqttOption.value.deviceSn,
          ...formValues,
          queryStartTime,
          queryEndTime,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'iot-cloudLog-index',
};

const [BasicTable] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
</script>

<template>
  <Page>
    <BasicTable />
  </Page>
</template>
